<template>
  <inline-Modal
    :visible="visible"
    :title="filterTitle()"
    :showOk="false"
    @cancel="goBack()"
  >
    <div class="button-groups">
      <a-button
        type="primary"
        :loading="submitLoading"
        v-if="pageOperate == 4 && zancun"
        @click="handleTemporarilyStore()"
      >
        暂存
      </a-button>
      <!--  -->
      <a-button
        type="primary"
        :loading="submitLoading"
        @click="handelSubmit()"
        v-if="[1, 2, 4].includes(pageOperate)"
      >
        {{ zancun ? "提交" : "确定" }}
      </a-button>
    </div>
    <!--  -->
    <div class="example" v-if="submitLoading">
      <a-spin> </a-spin>
      提交中，请稍后...
    </div>
    <!--  -->
    <div class="wrap-page-container">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="false"
      >
        <!-- 新增、编辑数据 -->
        <div class="sub-title" v-if="pageOperate == 4">基本信息</div>
        <div class="warp-container">
          <a-row>
            <a-col :span="[2, 9].includes(moduleSource()) ? 8 : 12">
              <a-form-model-item
                label="专业"
                prop="major"
                :rules="{
                  required: pageOperate == 4 || pageOperate == 3 ? false : true,
                  message: '请选择专业',
                }"
              >
                <a-select
                  placeholder="请选择"
                  v-model="form.major"
                  :disabled="isDisabled"
                  showSearch
                  allowClear
                  :filter-option="filterOption"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in majorSource"
                    :key="item.dicItemCode"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col
              :span="[2, 9].includes(moduleSource()) ? 8 : 12"
              v-if="moduleSource() == 8"
            >
              <a-form-model-item
                label="分项工程"
                prop="section"
                :rules="{
                  required: pageOperate == 4 || pageOperate == 3 ? false : true,
                  message: '请选择分项工程',
                }"
              >
                <a-select
                  placeholder="请选择"
                  v-model="form.section"
                  :disabled="isDisabled"
                  showSearch
                  allowClear
                  :filter-option="filterOption"
                  @blur="handleBlur($event)"
                  @change="handleChange($event)"
                  @search="handleSearch($event)"
                >
                  <a-select-option
                    :value="item.dicItemCode"
                    v-for="item in sectionSource"
                    :key="item.dicItemCode"
                  >
                    {{ item.dicItemName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="[2, 9].includes(moduleSource()) ? 8 : 12">
              <a-form-model-item label="提交人">
                <a-input v-model="form.creator" disabled></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="[2, 9].includes(moduleSource()) ? 8 : 12">
              <a-form-model-item label="提交时间">
                <a-input v-model="form.createTime" disabled></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item label="图纸">
            <div class="drawing-container">
              <div class="left-warp-container">
                <div class="tree-container">
                  <a-empty v-if="treeData.length == 0" :description="false" />
                  <a-tree
                    v-else
                    v-model="checkedKeys"
                    show-icon
                    show-line
                    :expanded-keys="expandedKeys"
                    :auto-expand-parent="autoExpandParent"
                    :selected-keys="selectedKeys"
                    :tree-data="treeData"
                    :replaceFields="{
                      children: 'children',
                      title: 'nodeName',
                      key: 'uuid',
                    }"
                    @expand="onExpand"
                    @select="onSelect"
                  >
                    <!-- 自定义图标 -->
                    <template slot="custom" slot-scope="{ expanded }">
                      <a-icon
                        :type="expanded ? 'folder-open' : 'folder'"
                        theme="filled"
                      />
                    </template>
                    <template
                      slot="title"
                      slot-scope="{ nodeName, id, uuid, delBtn, versionMain }"
                    >
                      <div class="custom-tree-title-warp">
                        <div class="title" :title="nodeName">
                          {{ nodeName }}
                        </div>
                        <div class="operate" v-if="isPageOperate">
                          <!-- 新增 -->
                          <icon-font
                            type="icon-xinjianwenjianjia"
                            class="add-file-button"
                            @click.stop="addFolder(id)"
                            v-if="versionMain != 1"
                          ></icon-font>
                          <!-- 编辑 -->
                          <a-icon
                            type="edit"
                            class="edit-btn"
                            @click.stop="editFolder(nodeName, uuid)"
                            v-if="delBtn == 0"
                          />
                          <!-- 删除 -->
                          <a-icon
                            type="delete"
                            class="delete-btn"
                            @click.stop="deleteFolder(uuid, id)"
                            v-if="delBtn == 0"
                          />
                        </div>
                      </div>
                    </template>
                  </a-tree>
                </div>
                <!-- 类型2：方案设计  类型3：初步设计  类型4：施工图设计 不展示新增一级目录按钮 -->
                <div
                  class="add-button"
                  v-action="'table_add_' + moduleSource()"
                  @click="addFolder(0, '')"
                  v-if="
                    pageOperate != 3 &&
                      pageOperate != 4 &&
                      ![2, 3, 4].includes(moduleSource())
                  "
                >
                  <icon-font type="icon-plus"></icon-font> 新建目录
                </div>
              </div>
              <div class="right-warp-container">
                <div class="upload-groups">
                  <a-button
                    class="cu-btn-primary margin-bottom-xs"
                    icon="cloud-upload"
                    @click="uploadFolder()"
                    v-if="currentTreeNode.uploadBtn && isPageOperate"
                  >
                    上传
                  </a-button>
                  <a-button
                    class="cu-btn-primary margin-bottom-xs"
                    icon="file-zip"
                    @click="handleUploadZip()"
                    v-if="currentTreeNode.zipBtn && isPageOperate"
                  >
                    导入压缩包
                  </a-button>
                  <a-button
                    class="cu-btn-primary margin-bottom-xs"
                    icon="download"
                    @click="handleDownloadZip()"
                    v-if="[3, 4].includes(pageOperate)"
                    :loading="downloadLoading"
                    :disabled="downloadLoading"
                  >
                    {{ downloadLoading ? "下载中" : "下载" }}
                  </a-button>
                  <a-button
                    class="cu-btn-primary margin-bottom-xs"
                    icon="delete"
                    @click="handleBatchDeleteFile()"
                    v-if="
                      tableData.length > 0 &&
                        !showHeader &&
                        isPageOperate &&
                        currentTreeNode.uploadBtn
                    "
                  >
                    批量删除
                  </a-button>
                  <a-button
                    class="cu-btn-primary margin-bottom-xs"
                    @click="handleMoveModal()"
                    icon="drag"
                    v-if="
                      tableData.length > 0 &&
                        !showHeader &&
                        isPageOperate &&
                        currentTreeNode.uploadBtn
                    "
                  >
                    批量移动
                  </a-button>
                </div>
                <div class="table-file-container">
                  <div
                    class="drag-drop-container"
                    v-if="
                      currentTreeNode.id &&
                        currentTreeNode.uploadBtn &&
                        isPageOperate
                    "
                  >
                    <dragDropUpload
                      :treeItem="currentTreeNode"
                      @onRefresh="fileRefresh($event)"
                    ></dragDropUpload>
                  </div>
                  <vxe-table
                    ref="xTable"
                    height="99%"
                    align="center"
                    show-overflow
                    show-header-overflow
                    border="inner"
                    :data="tableData"
                    :column-config="{ resizable: true }"
                    size="small"
                    :loading="tableLoading"
                  >
                    <vxe-table-column
                      width="60"
                      v-if="!showHeader && isPageOperate"
                    >
                      <template #header>
                        <a-checkbox
                          v-model="allChecked"
                          :indeterminate="indeterminate"
                          @change="allClick($event)"
                          :disabled="showHeader"
                        >
                        </a-checkbox>
                      </template>
                      <template #default="{ row }">
                        <a-checkbox
                          v-model="row.select"
                          @change="changeItem($event, row)"
                          :disabled="row.isDisabled"
                        >
                        </a-checkbox>
                      </template>
                    </vxe-table-column>
                    <vxe-column type="seq" width="80" title="序号"></vxe-column>
                    <vxe-column
                      title="文件名称"
                      field="fileName"
                      min-width="300"
                      align="left"
                    >
                      <template #default="{ row }">
                        <div class="table-file-name">
                          <div
                            class="icon"
                            :class="[getFileIconName(row.fileName)]"
                          ></div>
                          <div class="name" @click="previewFile(row)">
                            {{ row.fileName }}
                          </div>
                        </div>
                      </template>
                    </vxe-column>
                    <vxe-column field="creator" title="上传人"> </vxe-column>
                    <vxe-column field="createTime" title="上传时间">
                    </vxe-column>
                    <vxe-column
                      field="correlation"
                      title="关联模型"
                      width="130"
                      v-if="pageOperate == 3"
                    >
                      <template #default="{ row }">
                        <div
                          class="correlation-model"
                          :class="!row.dataSetId && 'no'"
                          v-if="row.previewWay == 'cad'"
                          @click="row.previewWay && viewModalCad(row)"
                        >
                          <icon-font
                            :type="
                              row.dataSetId
                                ? 'icon-wancheng'
                                : 'icon-weiwancheng'
                            "
                            class="location-button"
                          ></icon-font>
                          {{ row | relevanceText }}
                        </div>
                        <div v-else>-</div>
                      </template>
                    </vxe-column>
                    <vxe-column
                      field="operate"
                      fixed="right"
                      width="80"
                      align="left"
                      title="操作"
                    >
                      <template #default="{ row ,rowIndex}">
                        <div class="files-icon">
                          <!-- 关联模型 -->
                          <a-tooltip
                            placement="top"
                            v-if="row.previewWay == 'cad' && pageOperate == 3"
                          >
                            <template slot="title">
                              关联模型
                            </template>
                            <icon-fonts
                              icon="icon-guanlian"
                              @change="handleAgain(row)"
                            />
                          </a-tooltip>
                          <!-- 预览 -->
                          <a-tooltip placement="top">
                            <template slot="title">
                              预览
                            </template>
                            <a-icon type="eye" @click="previewFile(row)" />
                          </a-tooltip>
                          <!-- 预览 -->
                          <a-tooltip
                            placement="top"
                            v-if="
                              [1, 2].includes(pageOperate) &&
                                row.versionMain != 1
                            "
                          >
                            <template slot="title">
                              删除
                            </template>
                            <a-icon
                              type="delete"
                              class="delete-btn"
                              @click="deleteFile(row, rowIndex)"
                            />
                          </a-tooltip>
                        </div>
                      </template>
                    </vxe-column>
                  </vxe-table>
                </div>
              </div>
            </div>
          </a-form-model-item>
        </div>
        <!-- 审批数据 -->
        <template v-if="pageOperate == 4 && form.nodeDesc.includes('[审批]')">
          <a-divider />
          <div class="sub-title">审批信息</div>
          <div class="warp-container">
            <a-row>
              <a-col :span="8">
                <a-form-model-item
                  label="审批结果"
                  prop="operate"
                  :rules="{
                    required: true,
                    message: '请选择审批结果',
                  }"
                >
                  <a-radio-group v-model="form.operate">
                    <a-radio :value="2">
                      通过
                    </a-radio>
                    <a-radio :value="3">
                      驳回
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <!-- 驳回展示 -->
              <a-col
                :span="8"
                v-if="form.operate == 3 && backNodeSource.length > 0"
              >
                <a-form-model-item
                  label="驳回节点"
                  prop="nodeId"
                  :rules="{
                    required: true,
                    message: '请选择驳回节点',
                  }"
                >
                  <a-select
                    placeholder="请选择"
                    v-model="form.nodeId"
                    showSearch
                    allowClear
                    :filter-option="filterOption"
                  >
                    <a-select-option
                      :value="item.nodeId"
                      v-for="item in backNodeSource"
                      :key="item.dicItemCode"
                    >
                      {{ item.nodeDesc }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-form-model-item label="审批意见" prop="reason">
              <a-textarea
                placeholder="请输入"
                :rows="4"
                v-model="form.reason"
              />
            </a-form-model-item>
          </div>
        </template>
      </a-form-model>
    </div>
    <!-- 新增、编辑弹窗 -->
    <addModal
      :visible.sync="addModal.visible"
      :operate="addModal.operate"
      :pid="addModal.pid"
      :nodeName="addModal.nodeName"
      :foreignKey="addModal.uuid"
      @onRefresh="folderRefresh($event)"
    ></addModal>
    <!-- 上传弹窗 -->
    <uploadModal
      :visible.sync="uploadModal.visible"
      :operate="uploadModal.operate"
      :treeItem="currentTreeNode"
      :parameter="uploadModal.row"
      @onRefresh="fileRefresh($event)"
    ></uploadModal>
    <!-- 上传压缩包 -->
    <uploadZipModal
      :visible.sync="uploadZipModal.visible"
      :treeItem="currentTreeNode"
      @change="zipModalChange($event)"
    ></uploadZipModal>
    <!-- 普通附件预览 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
    <!-- 批量移动 -->
    <moveModal
      :visible.sync="moveModal.visible"
      :parameter="moveModal.source"
      @moveChange="handleMoveChange($event)"
    ></moveModal>
    <!-- 关联模型 -->
    <associationModel
      :visible.sync="associationModel.visible"
      :row="associationModel.row"
      @change="handleUploadTable()"
    ></associationModel>
  </inline-Modal>
</template>

<script>
import moment from "moment";
import { Icon } from "ant-design-vue";
import iconfrontjs from "@/assets/IconFont/iconfont.js";
const iconFrontUrl = iconfrontjs;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: iconFrontUrl,
});
import {
  addAttributeByKey,
  flatTreeData,
  getFileIconName,
  getNodeByKey,
} from "@/utils/util.js";
import cloneDeep from "lodash.clonedeep";
import { axios } from "@/utils/request";
import { mapGetters } from "vuex";
import { getToken, downLoadBatchFileByArraybuffer } from "@/utils/TopVUI";
//新建弹窗
import addModal from "./addModal";
//上传弹窗
import uploadModal from "./uploadModal";
//上传压缩包
import uploadZipModal from "./uploadZipModal";
//关联模型
import associationModel from "./associationModel";
//拖拽上传
import dragDropUpload from "./dragDropUpload";
//批量移动
import moveModal from "./moveModal";
//预览
import previewModal from "@/pages/document/minio/previewModal";
import { getDicItemByCode } from "@/api/common.js";
import { exportPermit } from "@/api/engineering";
export default {
  inject: ["moduleSource"],
  components: {
    IconFont,
    addModal,
    uploadModal,
    uploadZipModal,
    previewModal,
    associationModel,
    dragDropUpload,
    moveModal,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
    //1新增 2编辑 3查看
    pageOperate: {
      type: [String, Number],
      default: 1,
    },
    //返回按钮
    isBackButton: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      //表单
      isDisabled: false,
      submitLoading: false,
      form: {
        uuid: "",
        //专业
        major: undefined,
        //分项工程
        section: undefined,
        //审批结果
        operate: "",
        //驳回节点
        nodeId: undefined,
        //审批意见
        reason: "",
        //节点名称
        nodeDesc: "",
      },
      rules: {},
      //图纸
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      currentTreeNode: {},
      //表格
      tableData: [],
      tableLoading: false,
      pager: {
        page: 1,
        pageSize: 999,
        total: 0,
      },
      //专业
      majorSource: [],
      //分项工程
      sectionSource: [],
      //返回节点
      backNodeSource: [],
      //目录
      contentsAddIds: [],
      contentsDeleteIds: [],
      //文件
      fileAddIds: [],
      fileDeleteIds: [],
      //新增编辑
      addModal: {
        visible: false,
        operate: 1,
        pid: "",
        nodeName: "",
        uuid: "",
      },
      //复选框
      allChecked: false,
      indeterminate: false,
      checkRowKeys: [],
      //上传
      uploadModal: {
        visible: false,
        operate: 1,
        row: {},
      },
      //上传压缩包
      uploadZipModal: {
        visible: false,
        fileList: [],
        treeData: [],
      },
      //下载
      downloadLoading: false,
      //是否显示表全选按钮
      showHeader: false,
      //批量移动弹窗
      moveModal: {
        visible: false,
        source: {},
        removeFileIdLs: [],
      },
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //关联模型
      associationModel: {
        visible: false,
        row: {},
      },
      //暂存按钮权限
      zancun: false,
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    //按钮操作
    isPageOperate() {
      if (this.pageOperate == 3) {
        return false;
      } else if (
        //审批操作时，并且是类型2：方案设计  类型3：初步设计  类型4：施工图设计 可以新增编辑删除树和表格
        this.pageOperate == 4 &&
        [2, 3, 4].includes(this.moduleSource())
      ) {
        return true;
      } else if (this.pageOperate == 1 || this.pageOperate == 2) {
        return true;
      } else {
        return false;
      }
    },
  },
  filters: {
    relevanceText(row) {
      let { dataSetId } = row;
      if (dataSetId) {
        return "已关联";
      } else {
        return "未关联";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    getFileIconName,
    filterTitle() {
      let { pageOperate } = this;
      switch (pageOperate) {
        case 1:
          this.isDisabled = false;
          return "新增";
        case 2:
          this.isDisabled = false;
          return "编辑";
        case 3:
          this.isDisabled = true;
          return "查看";
        case 4:
          this.isDisabled = true;
          return "审批";
        default:
          break;
      }
    },
    async getData() {
      //专业
      this.majorSource = await this.getDicCodeData("major");
      //分项工程
      this.sectionSource = await this.getDicCodeData("section");
      if (this.pageOperate == 1) {
        //新增
        this.getConfig();
      } else {
        //编辑、详情
        this.getDetail();
      }
    },
    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },
    handleBlur(value) {
      this.form.section = value;
    },
    handleSearch(value) {
      this.handleChange(value);
    },
    handleChange(value) {
      this.form.section = value != null && value != "" ? value : undefined;
    },

    //新增信息
    getConfig() {
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/schemeDesign/initConfigField?type=${this.moduleSource()}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.giveFormData(data);
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },
    //详情
    getDetail() {
      let { uuid } = this.parameter;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/schemeDesign/getDetailByUuid?uuid=${uuid}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.giveFormData(data);
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },
    //赋值
    giveFormData(data) {
      this.form = {
        uuid: data?.uuid,
        //专业
        major: data?.major ?? undefined,
        //分项工程
        section: data?.section ?? undefined,
        //提交人
        creator: data?.creator,
        //提交时间
        createTime: data?.createTimeStr,
        //审批结果
        operate: 2,
        //驳回节点
        nodeId: undefined,
        //审批意见
        reason: "",
        //节点名称
        nodeDesc: data?.nodeDesc,
      };
      //
      this.zancun = data.zancun;
      //
      this.backNodeSource = data?.backNode ?? [];
      this.getTreeData();
    },
    //新建文件夹
    addFolder(id) {
      this.addModal.operate = 1;
      this.addModal.pid = id;
      this.addModal.nodeName = "";
      this.addModal.uuid = this.form.uuid;
      this.addModal.visible = true;
    },
    //编辑文件夹
    editFolder(nodeName, uuid) {
      this.addModal.operate = 2;
      this.addModal.pid = uuid;
      this.addModal.nodeName = nodeName;
      this.addModal.uuid = this.form.uuid;
      this.addModal.visible = true;
    },
    //删除文件夹
    deleteFolder(uid = "", id) {
      let { uuid } = this.currentTreeNode;
      this.contentsDeleteIds.push(id);
      this.contentsAddIds = this.contentsAddIds.filter((v) => v != id);
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          return new Promise((resolve, reject) => {
            that
              .$post(`/probusiness/bimCadClassify/deleteData?uuid=${uid}`)
              .then((res) => {
                let { statusCode, message } = res;
                if (statusCode == 200) {
                  that.$message.success("删除成功！");
                  if (uuid == uid) {
                    that.currentTreeNode = {};
                    that.tableData = [];
                  }
                  that.getTreeData();
                } else {
                  that.$message.error(message ?? "删除失败，请稍后重试！");
                }
                resolve();
              })
              .catch((_) => {
                reject();
              })
              .finally((_) => {});
          }).catch(() => console.log("Oops errors!"));
        },
      });
    },
    //左侧树刷新
    folderRefresh(id) {
      this.contentsAddIds.push(id);
      this.getTreeData();
    },
    //查询左侧树
    getTreeData() {
      let { uuid = "" } = this.form;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/schemeDesign/getTreeByProCodeInner`,
            {
              uuid,
              type: this.moduleSource(),
              addClassifyIdLs: this.contentsAddIds,
              deleteClassifyIdLs: this.contentsDeleteIds,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            let source = data ?? [];
            let flatData = flatTreeData(source, "children");
            this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "children"
            );
            this.treeData = filterData ?? [];
            if (!this.currentTreeNode.uuid) {
              let { pageOperate } = this;
              if ([2, 3, 4].includes(this.moduleSource()) && pageOperate == 4) {
                let treeList = flatData.filter((v) => !v.disabled);
                this.currentTreeNode = treeList[treeList.length - 1] ?? {};
              } else {
                this.currentTreeNode = filterData?.[0] ?? {};
              }
            }
            this.selectedKeys = [this.currentTreeNode.uuid];
            this.handleUploadTable();
            resolve();
          })
          .catch((_) => {
            this.currentTreeNode = {};
            this.expandedKeys = [];
            this.treeData = [];
            reject();
          })
          .finally((_) => {});
      });
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //监听树形选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.handleUploadTable();
    },
    //查询上传表格
    handleUploadTable() {
      let { id } = this.currentTreeNode;
      let { uuid = "" } = this.form;
      let { removeFileIdLs } = this.moveModal;
      if (!id) {
        this.tableData = [];
        return;
      }
      this.tableLoading = true;
      axios
        .post(
          `/probusiness/bimCadFile/getListByForeignKey`,
          {
            classifyId: id,
            type: this.moduleSource(),
            uuid,
            addFileIdLs: this.fileAddIds,
            deleteFileIdLs: this.fileDeleteIds,
            removeFileIdLs,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { data } = res;
          this.tableData = data ?? [];
          this.tableData.forEach((item) => {
            if (this.checkRowKeys.includes(item.uuid)) {
              this.$set(item, "select", true);
              this.$set(item, "isDisabled", false);
            } else {
              this.$set(item, "select", false);
              if (item.versionMain == 1) {
                this.$set(item, "isDisabled", true);
              } else {
                this.$set(item, "isDisabled", false);
              }
            }
          });
          this.resetBatchCheckBox();
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally((_) => {
          this.tableLoading = false;
        });
    },
    //重置全选按钮
    resetBatchCheckBox() {
      this.showHeader = this.tableData.every((v) => v.versionMain == 1);
      let filterArray = this.tableData.filter((v) => v.versionMain != 1);
      try {
        filterArray.forEach((v) => {
          if (v.select) {
            throw v;
          }
        });
        this.indeterminate = false;
      } catch (error) {
        this.indeterminate = true;
      }
      const ids = filterArray.filter((item) => item.select).map((v) => v.uuid);
      if (ids.length == filterArray.length) {
        this.indeterminate = false;
      }
      if (filterArray.length > 0) {
        this.allChecked = filterArray.every((v) => v.select);
      } else {
        this.allChecked = false;
      }
    },

    //上传文件
    uploadFolder() {
      this.uploadModal.operate = 1;
      this.uploadModal.row = {};
      this.uploadModal.visible = true;
    },

    //监听压缩包弹窗
    zipModalChange(ev) {
      let { currentTreeNode } = this;
      let { fileList, treeData, addClassifyIdLs, addFileIdLs, fileInfo } = ev;
      this.uploadZipModal.fileList = fileList;
      this.uploadZipModal.treeData = treeData;
      this.uploadZipModal.addClassifyIdLs = addClassifyIdLs;
      this.uploadZipModal.fileInfo = fileInfo;
      this.uploadZipModal.addFileIdLs = addFileIdLs;
      let itemNode = getNodeByKey(
        currentTreeNode.uuid,
        "uuid",
        this.treeData,
        "children"
      );
      let zipFolderData = this.getFolderData(treeData);
      if (itemNode?.children) {
        itemNode.children.push(...zipFolderData);
      } else {
        itemNode.children = zipFolderData;
      }
      this.fileAddIds.push(...addFileIdLs);
      this.contentsAddIds.push(...addClassifyIdLs);

      this.getTreeData();
    },

    //过滤出所有文件夹数据
    getFolderData(data) {
      try {
        filterData(data);
        function filterData(source = []) {
          source.forEach((item) => {
            if (item.type === "folder") {
              if (item.children && item.children.length) {
                item.children = item.children.filter(
                  (v) => v.type === "folder"
                );
                filterData(item.children);
              }
            }
          });
        }
        throw data;
      } catch (data) {
        return data;
      }
    },

    //打开导入压缩包弹窗
    handleUploadZip() {
      this.uploadZipModal.visible = true;
    },

    handleMoveChange(data) {
      let index = this.moveModal.removeFileIdLs.findIndex(
        (item) => item.classifyId === data.classifyId
      );
      if (index !== -1) {
        this.moveModal.removeFileIdLs.splice(index, 1);
      }
      this.moveModal.removeFileIdLs.push(data);
      this.allChecked = false;
      this.indeterminate = false;
      this.checkRowKeys = [];
      this.handleUploadTable();
    },

    //批量移动
    handleMoveModal() {
      if (this.checkRowKeys.length == 0) {
        this.$message.warning("请选择需要移动的文件！");
        return;
      }
      let { form, contentsAddIds, contentsDeleteIds, checkRowKeys } = this;
      this.moveModal.source = {
        uuid: form.uuid,
        pageModule: this.moduleSource(),
        contentsAddIds,
        contentsDeleteIds,
        checkRowKeys,
      };
      this.moveModal.visible = true;
    },

    //文件删除
    deleteFile(row, index) {
      this.fileDeleteIds.push(row.uuid);
      this.tableData.splice(index, 1);
      this.fileAddIds = this.fileAddIds.filter((v) => v != row.uuid);
    },

    fileRefresh(uuid) {
      this.fileAddIds.push(uuid);
      this.handleUploadTable();
    },

    //批量删除文件
    handleBatchDeleteFile() {
      if (this.checkRowKeys.length == 0) {
        this.$message.warning("请选择需要删除的文件！");
        return;
      }
      this.checkRowKeys.forEach((v) => {
        this.fileDeleteIds.push(v);
      });
      this.tableData = this.tableData.filter(
        (v) => !this.checkRowKeys.includes(v.uuid)
      );
      this.checkRowKeys = [];
      this.resetBatchCheckBox();
    },

    //全选
    allClick() {
      this.indeterminate = false;
      if (this.allChecked) {
        this.tableData.forEach((v) => {
          if (v.versionMain != 1) {
            this.$set(v, "select", true);
          }
        });
        let filterArray = this.tableData.filter((v) => v.versionMain != 1);
        this.checkRowKeys = filterArray.map((v) => v.uuid);
      } else {
        this.tableData.forEach((v) => {
          this.$set(v, "select", false);
        });
        this.checkRowKeys = [];
      }
    },

    //单选
    changeItem(event, row) {
      let { checked } = event.target;
      let { uuid } = row;
      if (checked) {
        this.checkRowKeys.push(uuid);
        this.checkRowKeys = Array.from(new Set(this.checkRowKeys));
      } else {
        this.checkRowKeys = this.checkRowKeys.filter((v) => v != uuid);
      }
      let filterArray = this.tableData.filter((v) => v.versionMain != 1);
      this.allChecked = filterArray.every((v) => v.select);
      this.indeterminate =
        !!this.checkRowKeys.length &&
        this.checkRowKeys.length < filterArray.length;
    },

    //【压缩包】同步上传到黑洞
    uploadBlackHole(data = []) {
      return new Promise(async (resolve, reject) => {
        let { dfsFileUuid, uuid } = data;
        let { fileList } = this.uploadZipModal;
        let { file } = fileList.find((v) => v.dfsFileUuid == dfsFileUuid) || {};
        // console.log({ file, data, fileList });
        if (!file) {
          resolve();
        } else {
          let { name } = file;
          const lastDotIndex = name.lastIndexOf("/");
          let fileName = name.substring(lastDotIndex + 1);
          const fileData = await file.async("arraybuffer");
          let formData = new FormData();
          formData.append("uploadFile", new Blob([fileData]), fileName);
          axios
            .post(
              `/probusiness/bimCadFile/uploadCadFile?uuid=${uuid}`,
              formData,
              {
                headers: {
                  "Content-Type": "multipart/form-data",
                },
              }
            )
            .then(async (res) => {
              let { statusCode, data } = res;
              if (statusCode == 200) {
                // let itemRow = tableData.find((v) => v.uuid == id);
                if (data?.FileId) {
                  //大文件分片
                  let proms = [];
                  let chunks = this.sliceFile(fileData, fileName);
                  chunks.forEach(async (v) => {
                    let { chunk, index, filename } = v;
                    proms.push(() =>
                      this.bigFileUpload(chunk, index, data, filename)
                    );
                  });
                  // 使用Array.reduce()来串联这些Promise
                  const promiseChain = proms.reduce(
                    (previousPromise, currentFunction) => {
                      return previousPromise.then((result) => {
                        return currentFunction();
                      });
                    },
                    Promise.resolve()
                  );
                  promiseChain
                    .then((result) => {
                      let { statusCode, message } = result;
                      if (statusCode == 200) {
                        // this.$message.success(`上传成功！`);
                      } else {
                        // this.$message.error(
                        //   message ?? `上传失败，请稍后重试！`
                        // );
                      }
                    })
                    .catch((error) => {
                      //   this.$set(itemRow, "status", 3);
                      //   this.$message.error(`上传失败，请稍后重试！`);
                    })
                    .finally((_) => {
                      resolve();
                    });
                } else {
                  //   this.$set(itemRow, "status", 2);
                  resolve();
                }
              } else {
                // this.$set(itemRow, "status", 3);
                this.$message.error(res.message ?? `上传失败，请稍后重试！`);
                reject();
              }
            })
            .catch((_) => {
              reject();
            });
        }
      });
    },

    //【压缩包】大文件上传接口
    bigFileUpload(file, i, data, fileName) {
      let { FileDatald, FileId, Key } = data;
      let formData = new FormData();
      formData.append("FileId", FileId);
      formData.append("FileInfo", new Blob([file]), fileName);
      formData.append("FileDataId", FileDatald);
      formData.append("Key", Key);
      formData.append("BlobIndex", i);
      return new Promise((resolve, reject) => {
        console.log({ FileDatald, FileId, Key, i, file });
        axios
          .post(`/probusiness/bimCadFile/project/cadFile/append`, formData, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((res) => {
            let {} = res;
            console.log("res==xxxxx", res);
            resolve(res);
          })
          .catch((_) => {
            reject();
          });
      });
    },

    //【压缩包】分片
    sliceFile(arrayBuffer, filename) {
      const chunks = [];
      const chunkSize = 1024 * 1024 * 20;
      const totalSize = arrayBuffer.byteLength;
      const totalChunks = Math.ceil(totalSize / chunkSize);
      for (let i = 0; i < totalChunks; i++) {
        const start = i * chunkSize;
        const end = Math.min(start + chunkSize, totalSize);
        const chunk = arrayBuffer.slice(start, end);
        chunks.push({
          filename,
          chunk,
          index: i,
          total: totalChunks,
          size: chunk.byteLength,
        });
      }

      return chunks;
    },

    //表单暂存
    handleTemporarilyStore() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          let { fileInfo } = this.uploadZipModal;
          const uploadCadFilePromises = (fileInfo || []).map((item) => {
            return this.uploadBlackHole(item);
          });
          Promise.all(uploadCadFilePromises)
            .then(() => {
              console.log("uploadCadFilePromises == ok");
              this.storeFormData();
            })
            .catch((res) => {
              this.submitLoading = false;
            })
            .finally((_) => {});
        }
      });
    },

    //表单提交
    handelSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          let { pageOperate } = this;
          //审批
          if (pageOperate == 4) {
            if ([2, 3, 4].includes(this.moduleSource())) {
              let { fileInfo } = this.uploadZipModal;
              const uploadCadFilePromises = (fileInfo || []).map((item) => {
                return this.uploadBlackHole(item);
              });
              Promise.all(uploadCadFilePromises)
                .then(() => {
                  console.log("uploadCadFilePromises == ok");
                  this.approveFormData();
                })
                .catch(() => {
                  this.submitLoading = false;
                })
                .finally((_) => {});
            } else {
              this.approveFormData();
            }
          }
          //新增、编辑
          else {
            let { fileInfo } = this.uploadZipModal;
            const uploadCadFilePromises = (fileInfo || []).map((item) => {
              return this.uploadBlackHole(item);
            });
            Promise.all(uploadCadFilePromises)
              .then(() => {
                console.log("uploadCadFilePromises == ok");
                this.saveFormData();
              })
              .catch(() => {
                this.submitLoading = false;
              })
              .finally(() => {});
          }
        }
      });
    },

    //新增、编辑
    saveFormData() {
      let {
        form,
        contentsAddIds = [],
        contentsDeleteIds = [],
        fileAddIds = [],
        fileDeleteIds = [],
      } = this;
      let { removeFileIdLs } = this.moveModal;
      let formJson = {
        uuid: form.uuid,
        //专业
        major: form.major,
        //分项工程
        section: form.section,
        //目录新增
        addClassifyIdLs: contentsAddIds,
        //目录删除
        deleteClassifyIdLs: contentsDeleteIds,
        //文件新增
        addFileIdLs: fileAddIds,
        //文件删除
        deleteFileIdLs: fileDeleteIds,
        //文件移动
        removeFileIdLs: removeFileIdLs,
      };
      this.submitLoading = true;
      axios
        .post(`/probusiness/schemeDesign/updateData`, formJson, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("操作成功", 1.5);
            this.goBack();
          } else {
            this.$message.error(res?.message ?? "操作失败");
          }
        })
        .catch((_) => {
          this.$message.error(_?.message ?? "操作失败");
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //审批
    approveFormData() {
      let {
        form,
        contentsAddIds = [],
        contentsDeleteIds = [],
        fileAddIds = [],
        fileDeleteIds = [],
      } = this;
      let { removeFileIdLs } = this.moveModal;
      let formJson = {
        uuid: form.uuid,
        //审批结果
        operate: form.operate,
        //驳回节点
        nodeId: form.operate == 3 ? form?.nodeId ?? "" : "",
        //审批意见
        reason: form.reason,
        //目录新增
        addClassifyIdLs: contentsAddIds,
        //目录删除
        deleteClassifyIdLs: contentsDeleteIds,
        //文件新增
        addFileIdLs: fileAddIds,
        //文件删除
        deleteFileIdLs: fileDeleteIds,
        //文件移动
        removeFileIdLs: removeFileIdLs,
      };
      this.submitLoading = true;
      axios
        .post(`/probusiness/schemeDesign/approveData`, formJson, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("操作成功", 1.5);
            this.goBack();
          } else {
            this.$message.error(res?.message ?? "操作失败");
          }
        })
        .catch((_) => {
          this.$message.error(_?.message ?? "操作失败");
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //暂存
    storeFormData() {
      let {
        form,
        contentsAddIds = [],
        contentsDeleteIds = [],
        fileAddIds = [],
        fileDeleteIds = [],
      } = this;
      let { removeFileIdLs } = this.moveModal;
      let formJson = {
        uuid: form.uuid,
        //审批结果
        operate: form.operate,
        //驳回节点
        nodeId: form.operate == 3 ? form?.nodeId ?? "" : "",
        //审批意见
        reason: form.reason,
        //目录新增
        addClassifyIdLs: contentsAddIds,
        //目录删除
        deleteClassifyIdLs: contentsDeleteIds,
        //文件新增
        addFileIdLs: fileAddIds,
        //文件删除
        deleteFileIdLs: fileDeleteIds,
        //文件移动
        removeFileIdLs: removeFileIdLs,
      };
      this.submitLoading = true;
      axios
        .post(`/probusiness/schemeDesign/zancunData`, formJson, {
          headers: {
            "Content-Type": "application/json",
          },
        })
        .then((res) => {
          if (res.statusCode === 200 || res === 1) {
            this.$message.success("操作成功", 1.5);
            this.goBack();
          } else {
            this.$message.error(res?.message ?? "操作失败");
          }
        })
        .catch((_) => {
          this.$message.error(_?.message ?? "操作失败");
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //交底文件预览
    previewFile(row) {
      let { previewWay, uuid, fileInfo, unit, bhDataSetId } = row;
      let { fileName } = fileInfo;
      let domain = location.origin;
      switch (previewWay) {
        //cad预览
        case "cad":
          window.open(
            `${domain}/#/blackHole/previewCad?uuid=${uuid}&fileName=${fileName}&unit=${unit}`
          );
          return;
        // 模型预览
        case "model":
          bhDataSetId &&
            window.open(
              `${domain}/#/blackHole/viewDataSetSingleSimple?dataSetId=${bhDataSetId}&name=${fileName}`
            );
          return;
        // 普通文件预览
        case "kkview":
          this.viewFile(fileInfo);
          return;
        default:
          break;
      }
    },

    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //下载压缩包
    handleDownloadZip() {
      let { id, nodeName } = this.currentTreeNode;
      let { uuid } = this.form;
      this.downloadLoading = true;
      axios
        .post(
          `/probusiness/schemeDesign/exportZip?classifyId=${id}&uuid=${uuid}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
            apiType: "file",
            responseType: "arraybuffer",
          }
        )
        .then((data) => {
          downLoadBatchFileByArraybuffer(data, nodeName);
        })
        .catch()
        .finally((_) => {
          this.downloadLoading = false;
        });
    },

    //关联模型
    handleAgain(row) {
      this.associationModel.row = row;
      this.associationModel.visible = true;
    },

    //预览关联后的模型和cad
    viewModalCad(row) {
      let { dataSetId, componentId, fileName, uuid } = row;
      let domain = location.origin;
      window.open(
        `${domain}/#/blackHole/previewCadBim?dataSetId=${dataSetId}&nodeId=${componentId}&cadId=${uuid}&name=${fileName}`
      );
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    async goBack() {
      await this.$emit("update:visible", false);
      this.$emit("close");
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  /deep/.ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 140px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
    }
  }
  //
  .button-groups {
    position: absolute;
    top: 10px;
    right: 90px;
    /deep/.ant-btn {
      &:not(:last-child) {
        margin-right: 10px;
      }
    }
  }

  .example {
    text-align: center;
    background: rgba(0, 0, 0, 0.1);
    position: absolute;
    top: 53px;
    left: 0;
    min-height: 100%;
    width: 100%;
    z-index: 99;
    flex-direction: column;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .wrap-page-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    .sub-title {
      padding-left: 30px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      font-size: 18px;
      color: #333333;
    }

    .warp-container {
      padding-right: 110px;
    }
    .drawing-container {
      height: 562px;
      overflow: hidden;
      display: flex;
      .left-warp-container {
        width: 300px;
        flex-shrink: 0;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #d4d7d8;
        margin-right: 10px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .tree-container {
          flex: 1;
          overflow: auto;
          overflow-x: hidden;
          position: relative;
          padding: 10px;
          box-sizing: border-box;
          /deep/.ant-tree {
            .ant-tree-node-content-wrapper {
              &:hover {
                .operate {
                  .anticon {
                    display: inline-block !important;
                  }
                }
              }
            }
            li {
              width: 100%;
              .ant-tree-node-content-wrapper {
                position: relative;
                width: calc(100% - 25px);
                padding: 0;
                .ant-tree-iconEle {
                  color: #ffca28;
                  font-size: 16px;
                }
                .ant-tree-title {
                  overflow: hidden;
                  display: inline-block;
                  width: calc(100% - 26px);
                  .custom-tree-title-warp {
                    display: flex;
                    width: 100%;
                    .title {
                      flex: 1;
                      overflow: hidden;
                      overflow: hidden;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                    }
                    .operate {
                      flex-shrink: 0;
                      color: #8c8c8c;
                      .anticon {
                        display: none;
                        margin-right: 8px;
                        &:last-of-type {
                          margin-right: 0;
                        }
                      }
                      .add-file-button {
                        font-size: 15px;
                      }
                    }
                  }
                }
              }
            }
          }
          .ant-empty {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
          }
        }
        .add-button {
          cursor: pointer;
          width: 268px;
          height: 32px;
          background: #ffffff;
          border-radius: 4px 4px 4px 4px;
          border: 1px dashed #1677ff;
          margin: 0 auto;
          margin-bottom: 16px;
          font-weight: 400;
          font-size: 14px;
          color: #1677ff;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .right-warp-container {
        width: calc(100% - 310px);
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        .upload-groups {
          height: 48px;
        }
        .table-file-container {
          flex-shrink: 0;
          flex: 1;
          position: relative;
          .files-icon {
            .anticon {
              cursor: pointer;
              font-size: 18px;
              color: #1677ff;
              margin-right: 16px;
              &:last-of-type {
                margin-right: 0;
              }
            }
            .anticon-download {
              color: #239b53;
            }
            .anticon-delete {
              color: #e43d3d;
            }
          }
          .drag-drop-container {
            z-index: 22;
            position: absolute;
            left: 60px;
            height: 100%;
            width: 80%;
          }
          .correlation-model {
            color: #1677ff;
            font-size: 14px;
            cursor: pointer;
            &:hover {
              text-decoration: underline;
            }
            .anticon {
              color: #239b53;
              margin-right: 6px;
            }
            &.no {
              text-decoration: none;
              cursor: default;
              .anticon {
                color: #ff2d2d;
              }
            }
          }
        }
        .table-file-pager {
          flex-shrink: 0;
        }
      }
    }
  }
}
</style>
